package com.hzpd.hainan.module.news.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.BaseFragment;
import com.hzpd.hainan.app.MyActivitymanager;
import com.hzpd.hainan.custorm.NewsCancelDialog;
import com.hzpd.hainan.model.base.BaseEntity;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.news.NewsChannelBean;
import com.hzpd.hainan.model.news.NewsFlashEntity;
import com.hzpd.hainan.model.news.NewsListEntity;
import com.hzpd.hainan.model.video.VideoItemBean;
import com.hzpd.hainan.model.video.VideoItenEntity;
import com.hzpd.hainan.module.news.adapter.NewsItemListViewAdapter;
import com.hzpd.hainan.module.news.adapter.NewsItemListViewAdapterNew;
import com.hzpd.hainan.module.news.view.TopViewPagerView;
import com.hzpd.hainan.module.video.adapter.VideoRecycleAdapter;
import com.hzpd.hainan.module.video.utils.VideoPlayerHelper;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.DeviceUtils;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.PageCtrl;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/3.
 */

public class NewsItemFragmentNew extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.recycler_newslist_id)
    RecyclerView recyclerNewslistId;
    @BindView(R.id.swipe_news_id)
    SwipeRefreshLayout swipeNewsId;
    private NewsItemListViewAdapterNew adapter;
    private Boolean isFirstLoadFlash = true;
    private TopViewPagerView topViewPagerView;

    private VideoRecycleAdapter adapter_video;

    @Override
    public int setMyContentView() {
        return R.layout.news_prlistview_new;
    }

    public static final NewsItemFragmentNew newInstance(int position, NewsChannelBean newsChannelBean) {
        NewsItemFragmentNew fragment = new NewsItemFragmentNew();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putSerializable("bean", newsChannelBean);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void initView() {
        channelbean = (NewsChannelBean) getArguments().getSerializable("bean");
        position = getArguments().getInt("position");
        swipeNewsId.setOnRefreshListener(this);
        swipeNewsId.setColorSchemeColors(Color.parseColor("#4395DB"));
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerNewslistId.setLayoutManager(layoutManager);
        initAdapter();
    }

    private void initAdapter() {
        adapter_video = new VideoRecycleAdapter(null);
        adapter_video.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                VideoItemBean itemBean = (VideoItemBean) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.rl_id:
                        VideoPlayerHelper.getInstance().play((ViewGroup) view, itemBean.getVideourl(), position);
                        break;
                    case R.id.video_info_rl:
                        VideoPlayerHelper.getInstance().stop();
                        PageCtrl.start2VideoPlayActivity(activity, "videoItemFragment", itemBean);
                        break;
                }
            }
        });
        adapter = new NewsItemListViewAdapterNew(null);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, recyclerNewslistId);
        if (channelbean.getTid().equals("38")) {
            recyclerNewslistId.setAdapter(adapter_video);
        } else {
            recyclerNewslistId.setAdapter(adapter);
        }
    }

    private int position = -1;
    private int page = 1;
    private static int pageSize = 15;//
    // 是否刷新最新数据
    private boolean mFlagRefresh;
    private boolean isNeedRefresh = false;
    private boolean isRefresh = false;//是否首次加载
    private NewsChannelBean channelbean;
    private String mTitle;

    @Override
    public void initData() {
        LogUtils.i("position-->" + position);
        LogUtils.i("isNeedRefresh-->" + isNeedRefresh);
        if (0 == position || isNeedRefresh) {
            swipeNewsId.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlagRefresh = true;
                    if (channelbean.getTid().equals("38")) {
                        getVideoListData();
                    } else {
                        getServerList();
                        getFlash();
                    }
                }
            }, 800);
            isRefresh = true;
            isNeedRefresh = false;
        }

    }

    public void init() {
        if (!isRefresh && null != recyclerNewslistId) {
            swipeNewsId.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlagRefresh = true;
                    if (channelbean.getTid().equals("38")) {
                        getVideoListData();
                    } else {
                        getServerList();
                        getFlash();
                    }


                }
            }, 800);
            isRefresh = true;
            isNeedRefresh = false;
        }
    }

    public void setIsNeedRefresh() {
        isNeedRefresh = true;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        //
        page = 1;
        mFlagRefresh = true;
        if (channelbean.getTid().equals("38")) {
            getVideoListData();
        } else {
            getServerList();
            getFlash();
        }
    }

    private NewsCancelDialog dialog;

    //点击时间
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                addCount(newsBean);
                MyActivitymanager.pushActivity(activity, newsBean, channelbean.getTid(), "newsitem");
                break;
            case R.id.lose_interest_id:
                LogUtils.i("click");
                int[] arrayOfint = new int[2];
                view.getLocationOnScreen(arrayOfint);
                int x = arrayOfint[0];
                int y = arrayOfint[1];
                dialog = new NewsCancelDialog(activity, R.style.canceldialog, x, y, newsBean.getNid());
                dialog.show();
                break;
        }
    }

    //上拉加载更多
    @Override
    public void onLoadMoreRequested() {
//        swipeNewsId.setEnabled(false);


        LogUtils.e("加载更多");
        mFlagRefresh = false;
        page++;

        getServerList();
    }

    /**
     * 获取新闻数据
     */
    public void getServerList() {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        map.put("Page", page + "");
        LogUtils.i("uid-->" + page + "");
        map.put("PageSize", pageSize + "");
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
            LogUtils.i("uid-->" + spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));

        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));

        Factory.provideHttpService()
                .newslist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        if (mFlagRefresh) {
                            swipeNewsId.setRefreshing(false);
                        }

                        if ("200".equals(entity.code)) {
//                            if (entity.data.size()<15){
//                                page++;
//                                setListData(entity.data);
//                            }

                            if (mFlagRefresh) {
                                LogUtils.i("200-->saveAll");
                                DataSupport.deleteAll(NewsBean.class);
                                DataSupport.saveAll(entity.data);

                            }
                            setListData(entity.data);

                        } else {
//                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (mFlagRefresh) {
                            swipeNewsId.setRefreshing(false);
                            List<NewsBean> list = DataSupport.findAll(NewsBean.class);
                            setListData(list);
                        }
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });


    }

    public void setListData(List<NewsBean> list) {

        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }

        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }

    private void addCount(NewsBean nb) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        Factory.provideHttpService()
                .newsAddCount(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<BaseEntity, Boolean>() {
                    @Override
                    public Boolean call(BaseEntity entity) {
                        LogUtils.i("addcount-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity entity) {
                        LogUtils.i("addcount-->" + entity.msg);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("addcount-->失败" + throwable.toString());
                    }
                });

    }

    //获取幻灯
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        Factory.provideHttpService()
                .newsFlashlist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsFlashEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("flash--200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsFlashEntity>() {
                    @Override
                    public void call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->成功");
                        if (isFirstLoadFlash) {
                            topViewPagerView = TopViewPagerView.instance(activity);
                            isFirstLoadFlash = false;
                            adapter.addHeaderView(topViewPagerView.getView());
                            topViewPagerView.reFreshFlashData(entity.data.flash);
                        } else {
                            topViewPagerView.reFreshFlashData(entity.data.flash);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        adapter.removeAllHeaderView();
                        LogUtils.i("flash--200-->失败" + throwable.toString());
                    }
                });


    }

    /**
     * 获取视频列表数据
     */
    private void getVideoListData() {
        Map<String, String> map = new HashMap();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
//        map.put("PageSize", pageSize+"");
        Factory.provideHttpService().videoList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<VideoItenEntity>() {
                    @Override
                    public void call(VideoItenEntity entity) {
                        setListData_video(entity.data);
                        if (mFlagRefresh) {
                            LogUtils.i("200-->saveAll");
                            DataSupport.deleteAll(VideoItemBean.class);
                            DataSupport.saveAll(entity.data);
                        }
                        swipeNewsId.setRefreshing(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (mFlagRefresh) {
                            List<VideoItemBean> list = DataSupport.findAll(VideoItemBean.class);
                            setListData_video(list);
                        }
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });
    }

    public void setListData_video(List<VideoItemBean> list) {

        if (mFlagRefresh) {
            adapter_video.setNewData(list);
            adapter_video.notifyDataSetChanged();
        } else {
            adapter_video.addData(list);
            adapter_video.notifyDataSetChanged();
            adapter_video.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter_video.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter_video.loadMoreEnd(true);
        }
        swipeNewsId.setEnabled(true);


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            VideoPlayerHelper.getInstance().stop();
        }
    }

}
